/**
 * Name:search.js
 * Author:gene.jiang
 * E-mail:1013195469@qq.com
 * Website:http://www.jianggujin.com/
 * LICENSE:Apache v2 License
 * Description:搜索模块
 */
layui.define(['jquery', 'tool', 'gform', 'geneconfig'], function(exports) {
    var $ = layui.jquery,
        _gform_ = layui.gform,
        _multivalue_ = layui.multivalue,
        _geneconfig_ = layui.geneconfig,
        _body_ = $('body'),
        _tool_ = layui.tool;
    layui.link(_geneconfig_.getModulePath() + '/css/search.css');
    var Search = function(options) {
        this.__render(options);
    };
    Search.fn = Search.prototype;

    function renderKeywordStyle(_that, _formOpt) {
        var _elem = _that._container,
            _header = $('<div class="gene-search-header"></div>'),
            _keyword = $('<div class="gene-search-keyword"></div>'),
            _inputs = $('<div class="gene-search-inputs"></div>'),
            _keywordOpt = _formOpt.keyword || {},
            _keywordInput = _that._keywordInput = $('<input type="text" class="layui-input">'),
            _keywordButton = $('<button gene-search-internal gene-event="search"></button>'),
            _hasMore = _that._hasMore = _formOpt.rows && _formOpt.rows.length,
            _more,
            _moreIcon;
        if(_keywordOpt.width) {
            _keywordInput.css('width', _keywordOpt.width + "px");
        }
        _keywordInput.attr('name', _keywordOpt.name || 'keyword').attr('placeholder', _keywordOpt.placeholder || '搜索关键字..').appendTo(_keyword);
        if(!!_keywordOpt.icon) {
            _keywordButton.html('<i class="layui-icon">' + _keywordOpt.icon + '</i>');
        } else if(!!_keywordOpt.eIcon) {
            _keywordButton.html(_keywordOpt.eIcon);
        } else {
            _keywordButton.html('<i class="layui-icon">&#xe615;</i></div>');
        }
        _keyword.append(_keywordButton);
        _inputs.append(_keyword);
        if(_hasMore) {
            _more = $('<div class="gene-search-more"></div>');
            _moreIcon = _that._moreIcon = $('<i class="layui-icon">&#xe61a;</i>');
            _more.append($('<span></span>').text(_keywordOpt.moreText || '更多筛选')).append(_moreIcon).appendTo(_inputs);

            var _rows = _formOpt.rows,
                _disableDefault = _formOpt.disableDefault === false,
                _moreBody = _that._moreBody = $('<div class="gene-search-more-body layui-anim layui-anim-upbit"></div>'),
                _moreBodyContent = $('<div class="gene-search-more-body-content"></div>');
            _moreBody.append(_moreBodyContent);
            _elem.append(_moreBody);
            _that._searchForm = _gform_.render({
                elem: _moreBodyContent,
                rows: _rows
            });
            if(_disableDefault === false) {
                var _footer = $('<div class="gene-search-more-body-footer"></div>'),
                    _defaultBtn = $('<button gene-search-internal gene-event="confirm" class="layui-btn layui-btn-sm"></button>');
                _defaultBtn.text(_formOpt.defaultText || '确定').appendTo(_footer);
                _footer.appendTo(_moreBody);
            }

            _more.click(function() {
                if(_moreBody.is(":hidden")) {
                    _that.__showMore();
                } else {
                    _that.__hideMore();
                }
            });
        } else {
            _inputs.css({
                'right': '0px',
                'padding': '10px 0px 10px 10px'
            });
        }

        !!_that._btns && _header.append(_that._btns);
        _header.append(_inputs);
        if(_keywordOpt.layout !== 'r') {
            //从左向右
            !!_that._btns && _that._btns.css('right', '0px');
            _inputs.css('right', 'auto');
            !!_moreBody && _moreBody.css('right', 'auto');
        }
        _elem.prepend(_header);
    }

    function renderNormalStyle(_that, _formOpt) {
        var _elem = _that._container,
            _form,
            _rows = _formOpt.rows,
            _hasForm = _that._hasForm = _rows && _rows.length,
            _disableDefault = _formOpt.disableDefault === false;
        if(_hasForm) {
            _form = $('<div class="gene-search-form"></div>');
            _elem.append(_form);
            _that._searchForm = _gform_.render({
                elem: _form,
                rows: _rows
            });

            if(_disableDefault === false) {
                var _footer = $('<div class="gene-search-form-footer"></div>'),
                    _defaultBtn = $('<button gene-search-internal gene-event="confirm" class="layui-btn layui-btn-sm"></button>');
                _defaultBtn.text(_formOpt.defaultText || '确定').appendTo(_footer);
                _footer.appendTo(_elem);
            }
        }

        !!_that._btns && _elem.append(_that._btns);
    }
    Search.fn.__render = function(options) {
        if(this._initialized) {
            layui.hint().error('Search已经初始化！');
            return;
        }
        options = options || {};
        if(!!options.elem) {
            this._container = $(options.elem);
            //存在配置的容器
            if(!this._container.length) {
                this._container = undefined;
            }
        }
        if(!this._container) {
            //选取默认容器
            this._container = _body_.find('div[gene-search]');
        }
        if(!this._container || !this._container.length) {
            layui.hint().error('Search没有正常初始化！');
            return;
        }
        this._container = this._container.eq(0);
        var _that = this,
            _elem = this._container,
            _callback = options.callback;

        _elem.empty();
        _elem.addClass('gene-search');

        //初始化按钮组
        var _btnOpt = options.btns,
            _btns = null;
        if(_btnOpt && $.isArray(_btnOpt.items)) {
            _btns = _that._btns = $('<div class="gene-search-btns"></div>');
            if(_btnOpt.useGroup) {
                _btns.addClass('layui-btn-group');
            }
            $.each(_btnOpt.items, function(i, item) {
                var _a = $('<a href="javascript:;" class="layui-btn layui-btn-sm" gene-search-btn></a>');
                if(!!item.event) {
                    _a.attr('gene-event', item.event);
                }
                if(!!item.href) {
                    _a.attr('href', item.href);
                }
                if(!!item.skin) {
                    _a.addClass('layui-btn-' + item.skin);
                }
                if(!!item.attr) {
                    _a.attr(item.attr);
                }
                if(!!item.icon) {
                    _a.html('<i class="layui-icon">' + item.icon + '</i>');
                } else if(!!item.eIcon) {
                    _a.html(item.eIcon);
                }
                $('<span></span>').html(item.text).appendTo(_a);
                _btns.append(_a);
            });
        }

        //初始化搜索部分关键字与表单
        var _formOpt = options.form || {};
        //判断是否有关键字输入项，只要配置就当做单行模式处理
        if(_formOpt.keyword) {
            renderKeywordStyle(_that, _formOpt);
        } else {
            renderNormalStyle(_that, _formOpt);
        }

        //初始化基本事件
        //内置
        _elem.on('click', 'button[gene-search-internal]', function() {
            var $this = $(this),
                event = $this.attr('gene-event');
            if('search' == event || 'confirm' == event) {
                if('confirm' == event) {
                    if(_that._searchForm) {
                        var _form = _that._searchForm;
                        if(!_form.verify()) {
                            return;
                        }
                    }
                }
                _that.__hideMore();
                if(typeof _callback.onSearch == 'function') {
                    var _multivalue = _that._searchForm && _that._searchForm.serializeFieldValue({
                            trimEmptyVal: true
                        }),
                        _name = _that._keywordInput && _that._keywordInput.attr('name'),
                        _keywordVal;
                    _multivalue = _multivalue || _multivalue_.newMultiValue();
                    !!_name && (_keywordVal = _that._keywordInput.val()) !== '' && _multivalue.put(_name, _keywordVal);
                    _callback.onSearch(_multivalue);
                }
            }
        });
        //自定义按钮命令
        _elem.on('click', 'a[gene-search-btn]', function(e) {
            var $this = $(this),
                event = $this.attr('gene-event');
            if(typeof _callback.onClick == 'function') {
                _callback.onClick($this, event, e);
            }
        });
        _that._initialized = true;

        return _that;
    };
    Search.fn.__showMore = function() {
        if(this._hasMore) {
            this._moreBody && this._moreBody.show();
            this._moreIcon && this._moreIcon.html('&#xe619;');
        }
    };
    Search.fn.__hideMore = function() {
        if(this._hasMore) {
            this._moreBody && this._moreBody.hide(300);
            this._moreIcon && this._moreIcon.html('&#xe61a;');
        }
    };

    function SearchExport() {}
    SearchExport.prototype.render = function(options) {
        return new Search(options);
    };
    exports('search', new SearchExport());
});